﻿using Mes.Domain.BoundedContext;
using Microsoft.EntityFrameworkCore;

namespace Mes.Infrastructure.Data.BoundedContext.Extensions
{
    public static class DbContextExtensions
    {
        public static Task<Paged<TEntity>> PagedEntityAsync<TEntity>(this DbContext dbCtx, int page, int itemsPerPage, string pageSql, object pageSqlArgs = null,
            string countSql = null, object countSqlArgs = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return Task.Run(() =>
            {
                var paged = dbCtx.Paged<TEntity>(page, itemsPerPage, pageSql, pageSqlArgs, countSql, countSqlArgs);
                return new Paged<TEntity>
                {
                    ItemsPerPage = paged.ItemsPerPage,
                    TotalPages = paged.TotalPages,
                    TotalItems = paged.TotalItems,
                    CurrentPage = paged.CurrentPage,
                    Items = paged.Items
                };
            }, cancellationToken);
        }

        public static Task<Paged<TReturn>> PagedEntityAsync<TFirst, TSecond, TReturn>(this DbContext dbCtx, Func<TFirst, TSecond, TReturn> map, int page, int itemsPerPage, string pageSql, object pageSqlArgs = null,
            string countSql = null, object countSqlArgs = null, string splitOn = "Id", long? totalCount = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            return Task.Run(() =>
            {
                var paged = dbCtx.Paged(map, page, itemsPerPage, pageSql, pageSqlArgs, countSql, countSqlArgs, splitOn, totalCount);
                return new Paged<TReturn>
                {
                    ItemsPerPage = paged.ItemsPerPage,
                    TotalPages = paged.TotalPages,
                    TotalItems = paged.TotalItems,
                    CurrentPage = paged.CurrentPage,
                    Items = paged.Items
                };
            }, cancellationToken);
        }
    }
}
